package com.snoweagler.verify;

import com.snoweagler.pojo.Menu;
import com.snoweagler.pojo.User;
import com.snoweagler.service.MenuService;
import com.snoweagler.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.apache.commons.collections4.CollectionUtils;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            User user = userService.findOneByUserName(username);
            UserAuthir userAuthir = new UserAuthir();
            List<Menu> menus = menuService.selectByName(username);
            if (CollectionUtils.isNotEmpty(menus)) {
                List<GrantedAuthority> authorities = new ArrayList<>();
                for (Menu m : menus) {
                    if (StringUtils.isNotEmpty(m.getPerms())) {
                        authorities.add(new SimpleGrantedAuthority(m.getPerms()));
                    }
                }
                userAuthir.setGrantedAuthorities(authorities);
            }
            BeanUtils.copyProperties(userAuthir, user);

            return userAuthir;
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    }
}
